//
//  PlayerManger.m
//  SBPlayer
//
//  Created by 黄锋 on 15/8/17.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PlayerManger.h"
#import "MBProgressHUD.h"

@interface PlayerManger ()

@property(nonatomic, strong) MBProgressHUD *hud;
@property(nonatomic) CGRect rect;
@property(nonatomic) NSInteger index;

@property(nonatomic, strong) UIButton *playButton;
@property(nonatomic, strong) UISlider *slider;
@property(nonatomic, strong) UILabel *currentTime;
@property(nonatomic, strong) UILabel *totalTime;

@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic) CGFloat beginTime;

@end

@implementation PlayerManger

+ (instancetype)defaultManger
{
    static PlayerManger *m = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        m = [[PlayerManger alloc] init];
    });
    return m;
}

- (instancetype)init
{
    if (self = [super init]) {
        [self addNotification];
    }
    return self;
}

- (void)playWithURL:(NSString *)url frame:(CGRect)rect mediaType:(MediaType)mediaType
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(available) name:MPMovieDurationAvailableNotification object:self];
    [_timer invalidate];
    
    [_songView removeFromSuperview];
    [self.view removeFromSuperview];

    if (_startBlock) {
        _startBlock();
    }
    _mediaType = mediaType;
    _index++;
    _beginTime = 0;
    self.contentURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    _rect = rect;
    if (_mediaType == Song) {
        self.view.frame = CGRectZero;
        _songView = [[UIView alloc] initWithFrame:rect];
        _songView.backgroundColor = [UIColor clearColor];
        [_songView addSubview:self.view];
        [self creatPlayButtonWithHud];
    } else if (_mediaType == Vedio) {
        self.view.frame = rect;
        self.view.backgroundColor = [UIColor clearColor];
        self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight  | UIViewAutoresizingFlexibleWidth;
        self.controlStyle = MPMovieControlStyleEmbedded;
        self.scalingMode = MPMovieScalingModeAspectFit;
        self.initialPlaybackTime = -1.0;
        if (url) {
            [self creatHud];
        }
    }
    //[self play];
}

- (void)creatSongView
{
    //UIButton *playButton = (UIButton *)[_songView viewWithTag:10000];
    _playButton.selected = YES;

    //NSLog(@"%f, %F, %F, %f, %f, %f", _playButton.transform.a, _playButton.transform.b, _playButton.transform.c, _playButton.transform.d, _playButton.transform.tx, _playButton.transform.ty);
    
    [UIView animateWithDuration:.5 animations:^{
        _playButton.frame = CGRectMake(0, 0, 46, 46);
        _playButton.transform = CGAffineTransformRotate(_playButton.transform, M_PI);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:.5 animations:^{
            _playButton.transform = CGAffineTransformRotate(_playButton.transform, M_PI);
        }];

        if (!_slider) {
            _slider = [[UISlider alloc] initWithFrame:CGRectMake(45, 18, _rect.size.width - 50, 10)];
           // _slider.tag = 20000;
            [_slider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
            _slider.minimumTrackTintColor = [UIColor redColor];
            [_slider addTarget:self action:@selector(setTimeTo:) forControlEvents:UIControlEventValueChanged];
        }
        _slider.value = 0;
        [_songView addSubview:_slider];
        
//        self.currentTime = [[UILabel alloc] initWithFrame:CGRectMake(47, _rect.size.height - 15, 30, 13)];
//        _currentTime.textColor = [UIColor whiteColor];
//        _currentTime.adjustsFontSizeToFitWidth = YES;
//        _currentTime.text = @"00:00";
        if (!_currentTime) {
            _currentTime = [[UILabel alloc] initWithFrame:CGRectMake(47, _rect.size.height - 15, 30, 13)];
            _currentTime.textColor = [UIColor whiteColor];
            _currentTime.adjustsFontSizeToFitWidth = YES;
            //_currentTime.tag = 30000;
        }
        _currentTime.text = @"";
        [_songView addSubview:_currentTime];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(changeCurrentTime) userInfo:nil repeats:YES];
        if (!_totalTime) {
            _totalTime = [[UILabel alloc] initWithFrame:CGRectMake(_rect.size.width - 35, _rect.size.height - 15, 30, 13)];
            _totalTime.textColor = [UIColor whiteColor];
            _totalTime.adjustsFontSizeToFitWidth = YES;
        }
        _totalTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)self.duration / 60, (NSInteger)self.duration % 60];
        [_songView addSubview:_totalTime];
    });
}

- (void)changeCurrentTime
{
//    [UIView animateWithDuration:.5 animations:^{
//        _playButton.transform = CGAffineTransformRotate(_playButton.transform, M_PI);
//    }];
    NSArray *events = self.accessLog.events;
    MPMovieAccessLogEvent *currentEvent = [events lastObject];
    CGFloat time = _beginTime + currentEvent.durationWatched;
    //UILabel *currentTime = (UILabel *)[_songView viewWithTag:30000];
    _currentTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)time / 60, (NSInteger)time % 60];
    if (self.duration) {
        //UISlider *slider = (UISlider *)[_songView viewWithTag:20000];
        _slider.value = time / self.duration;
        _totalTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)self.duration / 60, (NSInteger)self.duration % 60];
    }
//    NSLog(@"111111111");
}

- (void)playOrPause:(UIButton *)sender
{
    if (sender.selected) {
        [self pause];
    } else {
        [self play];
    }
    sender.selected = !sender.selected;
}

- (void)setTimeTo:(UISlider *)sender
{
    _beginTime = self.duration * (double)(sender.value / sender.maximumValue);
    if (self.playbackState == MPMoviePlaybackStatePlaying) {
        [self pause];
    }
    [self setCurrentPlaybackTime:_beginTime];
    _playButton.selected = YES;
    [self play];
}

- (void)creatPlayButtonWithHud
{
    if (!_playButton) {
        self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _playButton.frame = CGRectMake(_rect.size.width / 2 - 23, 0, 46, 46);
        [_playButton setImage:[UIImage imageNamed:@"iconfont-bofang-1"] forState:UIControlStateNormal];
        [_playButton setImage:[UIImage imageNamed:@"iconfont-icon12"] forState:UIControlStateSelected];
        [_playButton addTarget:self action:@selector(playOrPause:) forControlEvents:UIControlEventTouchUpInside];
        //_playButton.tag = 10000;
        _playButton.selected = NO;
        _playButton.layer.masksToBounds = YES;
        _playButton.layer.cornerRadius = 23;
    }
    _playButton.frame = CGRectMake(_rect.size.width / 2 - 23, 0, 46, 46);
    [_songView addSubview:_playButton];
    [self creatHud];
}

- (void)creatHud
{
    if (_mediaType == Vedio) {
        _hud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:_hud];
    } else {
        //UIButton *playButton = (UIButton *)[_songView viewWithTag:10000];
        _hud = [[MBProgressHUD alloc] initWithView:_playButton];
        [_playButton addSubview:_hud];
    }
    [_hud show:YES];
    NSInteger index = _index;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (index == _index) {
//            NSArray *events = self.accessLog.events;
//            MPMovieAccessLogEvent *currentEvent = [events lastObject];
            //NSLog(@"playbackState:%ld", self.playbackState);
            if (self.playbackState == MPMoviePlaybackStateStopped) {
                [_hud removeFromSuperview];
                [_hud show:NO];
                [self.view removeFromSuperview];
                if (_mediaType == Song) {
                    [_timer invalidate];
                    [_songView removeFromSuperview];
                    if (_finishBlock) {
                        _finishBlock();
                    }
                }
            }
        }
    });
}

- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerPlaybackDidFinish) name:MPMoviePlayerPlaybackDidFinishNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(available) name:MPMovieDurationAvailableNotification object:self];
//    MPMovieNaturalSizeAvailableNotification
//    MPMovieDurationAvailableNotification
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(available) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)change:(NSNotification *)notification
{
    if (_mediaType == Vedio) {
        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        if (orientation == UIInterfaceOrientationLandscapeRight  || orientation ==UIInterfaceOrientationLandscapeLeft) {
            [self setFullscreen:YES animated:YES];
            self.view.frame = [UIScreen mainScreen].bounds;
        } else if (orientation == UIInterfaceOrientationPortrait  || orientation == UIInterfaceOrientationPortraitUpsideDown) {
            [self setFullscreen:NO animated:NO];
            self.view.frame = _rect;
        }
    }
}

- (void)playerPlaybackDidFinish
{
    NSLog(@"playerPlaybackDidFinish");
    if (_mediaType == Vedio) {
        [self setFullscreen:NO animated:NO];
        [self.view removeFromSuperview];
    } else {
        [_timer invalidate];
        [_songView removeFromSuperview];
    }
    if (_finishBlock) {
        _finishBlock();
    }
}

- (void)available
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieDurationAvailableNotification object:self];
    
    NSLog(@"******************************************");
    [_hud removeFromSuperview];
    [_hud show:NO];
    if (_mediaType == Vedio) {
        self.backgroundView.backgroundColor = [UIColor blackColor];
    } else if (_mediaType == Song) {
        [self creatSongView];
    }
    //[self prepareToPlay];
    [self play];
}


@end
